import React, { Component } from "react";
import store from "../../redux/store";
import {
  createIncrementAction,
  createDecrementAction,
} from "../../redux/count_action";
export default class Count extends Component {
  state = {
    count: 0,
  };
  componentDidMount() {
    store.subscribe(() => {
      this.setState({});
    });
  }
  add = () => {
    const { value } = this.selectNum;
    store.dispatch(createIncrementAction(value * 1));
  };
  subtract = () => {
    const { value } = this.selectNum;
    store.dispatch(createDecrementAction(value * 1));
  };
  addAndOdd = () => {
    if (store.getState() % 2 === 0) {
      return;
    }
    const { value } = this.selectNum;
    store.dispatch(createIncrementAction(value * 1));
  };
  asyncAdd = () => {
    setTimeout(() => {
      const { value } = this.selectNum;
      store.dispatch(createIncrementAction(value * 1));
    }, 500);
  };
  render() {
    // const { count } = this.state;
    return (
      <div>
        <h1>Count的值是:{store.getState()}</h1>
        <select ref={(c) => (this.selectNum = c)}>
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
        </select>
        <button onClick={this.add}>+</button>
        <button onClick={this.subtract}>-</button>
        <button onClick={this.addAndOdd}>oddAdd</button>
        <button onClick={this.asyncAdd}>asyncAdd</button>
      </div>
    );
  }
}

